package main

import (
	"context"
	"errors"
	pb "go_grpc/server/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
	"log"
	"net"
)

// hello server
type Server struct {
	pb.UnimplementedSayHelloServer
}

// 业务
func (s *Server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
	//获取元数据的信息
	md, ok := metadata.FromIncomingContext(ctx)
	println(ok)
	for s2, strings := range md {
		println("==============")
		println(s2)
		for _, s3 := range strings {
			println(s3)
		}
	}
	if !ok {
		return nil, errors.New("未传Token")
	}

	var appId string
	var appKey string

	if v, ok := md["appid"]; ok {
		appId = v[0]
	}

	if v, ok := md["appkey"]; ok {
		appKey = v[0]
	}

	if appId != "wulei" {
		return nil, errors.New("appId 错误")
	}
	if appKey != "123123" {
		return nil, errors.New("appKey 错误")
	}
	println("hello" + req.RequestName)
	return &pb.HelloResponse{ResponseMsg: "hello" + req.RequestName}, nil
}

//func main() {
//	cred, _ := credentials.NewServerTLSFromFile("D:\\goWork\\src\\go_grpc\\key\\test.pem",
//		"D:\\goWork\\src\\go_grpc\\key\\test.key")
//	//开启端口
//	listen, _ := net.Listen("tcp", ":9090")
//	// 创建 grpc
//	grpcServer := grpc.NewServer(grpc.Creds(cred))
//	//在 grpc 服务端中去注册我们自己编写的服务
//	pb.RegisterSayHelloServer(grpcServer, &Server{})
//	//启动服务
//	err := grpcServer.Serve(listen)
//	if err != nil {
//		log.Fatal("服务启动失败")
//		return
//	}
//}

func main() {
	//开启端口
	listen, _ := net.Listen("tcp", ":9090")
	// 创建 grpc
	grpcServer := grpc.NewServer(grpc.Creds(insecure.NewCredentials()))
	//在 grpc 服务端中去注册我们自己编写的服务
	pb.RegisterSayHelloServer(grpcServer, &Server{})
	//启动服务
	err := grpcServer.Serve(listen)
	if err != nil {
		log.Fatal("服务启动失败")
		return
	}
}
